package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//服务器
public class UdpEchoServer {
    private DatagramSocket socket;

    //传入端口号，固定服务器的位置
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //服务器启动代码
    public void start() throws IOException {
        System.out.println("服务器启动...");
        while(true) {
            //获取客户端的请求的数据报
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);

            //解析请求的响应，计算响应
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String response = process(request);

            //构建响应数据报
            //UDP 协议本身不保存对端的IP 和 端口号
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            //发送响应数据报
            socket.send(responsePacket);
            //打印日志
            System.out.printf("请求数据的IP 和 端口号[%s : %d]: request:%s response:%s\n", requestPacket.getAddress().toString(),
                    responsePacket.getPort(),request, response);
        }
    }

    //计算响应，这里是回显服务器，直接返回
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
